#-*-coding:utf-8-*-
from michelangelo import app
from michelangelo.database import Sms, db_session
import datetime
import yunpian
import json
import logging
from logging import Formatter
from logging.handlers import TimedRotatingFileHandler
from apscheduler.schedulers.blocking import BlockingScheduler

logger = logging.getLogger('Michelangelo_cron')


def send_by_yunpian(text, phone):
  text = text.encode('UTF-8')
  apikey = app.config['API_KEY']
  logger.info('cron send text {0} to phone {1}'.format(text, phone))
  return yunpian.send_sms(apikey, text, phone)

def scan_and_send(limit=20):
  now = datetime.datetime.now()
  sms_list = Sms.query.filter(Sms.status == Sms.REQUESTING, Sms.schedule_time <= now).limit(limit).all()
  for sms in sms_list:
    result_str = send_by_yunpian(sms.content, sms.phone)
    result= json.loads(result_str)
    status = Sms.ERROR
    if result['code'] == 0:
      status = Sms.SUCCESS
    #update sms status
    Sms.query.filter(Sms.id == sms.id).update(
      {
        Sms.status: status,
        Sms.result: result_str
      }
    )
  db_session.commit()

def init_logger():
  # enable apscheduler logger and st level to error
  logging.basicConfig()
  logging.getLogger("apscheduler.scheduler").setLevel(logging.ERROR)
  # create console handler and set level to info
  logger = logging.getLogger('Michelangelo_cron')
  handler = TimedRotatingFileHandler(app.config['CRON_LOG_FILE'], when="midnight")
  handler.suffix = '%Y-%m-%d'
  handler.setFormatter(Formatter(
    '%(asctime)s %(module)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
  ))
  logger.addHandler(handler)
  logger.setLevel(logging.INFO)


#scheduler
scheduler = BlockingScheduler()

@scheduler .scheduled_job('interval', seconds=2)
def sms_job():
  scan_and_send()

if __name__ == "__main__":
  init_logger()
  scheduler.start()
